package com.android.jay.lib_network.okhttp;

import com.android.jay.lib_network.okhttp.response.CommonFileCallback;
import com.android.jay.lib_network.okhttp.response.CommonJsonCallback;
import com.android.jay.lib_network.okhttp.response.listener.DisposeDataHandler;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Call;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by wzp on 2019/12/29 0029.
 * <p>
 * 描述  ：用来发送get post请求的工具类 包括设置一些请求的公共参数
 */
public class CommonOkhttpClient {
    //超时时间
    private final static int TIME_OUT = 30;
    private static OkHttpClient mOkhttpClient;

    //完成对 OKHTTPCLIENT 的初始化
    static {
        OkHttpClient.Builder okhttpClientBulider = new OkHttpClient.Builder();
        okhttpClientBulider.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                //返回true就是 不对任何域名做处理  hostname  可以查看 是否在白名单和黑名单
                return true;
            }
        });

        /**
         *
         * 拦截器添加的公共请求头
         * **/
        okhttpClientBulider.addInterceptor(new Interceptor() {
            @NotNull
            @Override
            public Response intercept(@NotNull Chain chain) throws IOException {
                //独特的
                Request request = chain.request()
                        .newBuilder()
                        .addHeader("User-Agent", "Imooc-Mobile")
                        .build();
                return chain.proceed(request);
            }
        });
        okhttpClientBulider.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
        okhttpClientBulider.readTimeout(TIME_OUT, TimeUnit.SECONDS);
        okhttpClientBulider.writeTimeout(TIME_OUT, TimeUnit.SECONDS);
        //允许重定向
        okhttpClientBulider.followRedirects(true);
        mOkhttpClient = okhttpClientBulider.build();
    }

    /**
     * get请求
     */

    public static Call get(Request request, DisposeDataHandler handler) {
        Call call = mOkhttpClient.newCall(request);
        call.enqueue(new CommonJsonCallback(handler));
        return call;
    }

    /**
     * post请求
     */
    public static Call post(Request request, DisposeDataHandler handler) {
        Call call = mOkhttpClient.newCall(request);
        call.enqueue(new CommonJsonCallback(handler));
        return call;
    }

    /**
     * 文件请求请求
     */
    public static Call downloadFile(Request request, DisposeDataHandler handler) {
        Call call = mOkhttpClient.newCall(request);
        call.enqueue(new CommonFileCallback(handler));
        return call;
    }

}
